//
//  CacheMgr.m
//  carcareIOS
//
//  Created by ileo on 15/12/17.
//  Copyright © 2015年 baozun. All rights reserved.
//

#import "CacheMgr.h"
#import "JsonExtend.h"
#import "NSString+Encode.h"

@implementation CacheMgr

+(NSString *)tmpCachePathWithName:(NSString *)name{
    return [NSString stringWithFormat:@"%@/%@",[CacheMgr tmpCachePath],name];
}

+(NSString *)nonTmpCachePathWithName:(NSString *)name{
    return [NSString stringWithFormat:@"%@/%@",[CacheMgr nonTmpCachePath],name];
}

+(CGFloat)cacheSize{
    NSFileManager *manager = [NSFileManager defaultManager];
    long long folderSize = 0;
    NSArray *paths = @[[CacheMgr tmpCachePath],[CacheMgr nonTmpCachePath]];
    
    for (NSString *path in paths) {
        if ([manager fileExistsAtPath:path]) {
            NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
            NSString *fileName;
            while ((fileName = [childFilesEnumerator nextObject])) {
                NSString *filePath = [path stringByAppendingPathComponent:fileName];
                folderSize += [CacheMgr fileSizeAtFilePath:filePath];
            }
        }
    }
    return folderSize / (1024.0 * 1024.0);
}

+(void)clearCacheFinish:(void (^)())finish{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *paths = @[[CacheMgr tmpCachePath],[CacheMgr nonTmpCachePath]];
    for (NSString *path in paths) {
        if ([manager fileExistsAtPath:path]) {
            NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
            NSString *fileName;
            while ((fileName = [childFilesEnumerator nextObject])) {
                NSString *filePath = [path stringByAppendingPathComponent:fileName];
                [manager removeItemAtPath:filePath error:nil];
            }
        }
    }
    if (finish) {
        finish();
    }
}

#pragma mark -

+(NSString *)tmpCachePath{
    return NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
}

+(NSString *)nonTmpCachePath{
    return NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
}

+(long long)fileSizeAtFilePath:(NSString *)path{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}

@end


@implementation UIImage (Cache)

+(id)cacheDataWithName:(NSString *)name{
    return [UIImage imageWithData:[NSData dataWithContentsOfFile:[CacheMgr tmpCachePathWithName:name]]];
}

+(void)cacheImageWithURL:(NSString *)urlStr finish:(void (^)(UIImage *))finish{
    if (finish) {
        __block UIImage *image;
        NSString *fileName = [urlStr encodeWithMD5];
        if ((image = [UIImage cacheDataWithName:fileName])) {
            finish(image);
        }else{
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
                [data writeToFile:[CacheMgr tmpCachePathWithName:fileName] atomically:NO];
                dispatch_async(dispatch_get_main_queue(), ^{
                    image = [UIImage imageWithData:data];
                    finish(image);
                });
            });
        }
    }
}

@end

@implementation NSString (Cache)

-(BOOL)cacheWithName:(NSString *)name{
    return [self writeToFile:[CacheMgr nonTmpCachePathWithName:name] atomically:NO encoding:NSUTF8StringEncoding error:nil];
}

+(id)cacheDataWithName:(NSString *)name{
    return [NSString stringWithContentsOfFile:[CacheMgr nonTmpCachePathWithName:name] encoding:NSUTF8StringEncoding error:nil];
}

@end

@implementation NSArray (Cache)

-(BOOL)cacheWithName:(NSString *)name{
    NSString *json = [self jsonValue];
    return [json cacheWithName:name];
}

+(id)cacheDataWithName:(NSString *)name{
    NSString *json = [NSString cacheDataWithName:name];
    return [NSArray arrayWithJsonValue:json];
}

@end

@implementation NSDictionary (Cache)

-(BOOL)cacheWithName:(NSString *)name{
    NSString *json = [self jsonValue];
    return [json cacheWithName:name];
}

+(id)cacheDataWithName:(NSString *)name{
    NSString *json = [NSString cacheDataWithName:name];
    return [NSDictionary dictionaryWithJsonValue:json];
}

@end
